package com.mlnx.push.websocket.client;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by amanda.shan on 2019/12/3.
 */
public class ResponseFuture<T> {

    private final int opaque;

    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    private final long beginTimestamp = System.currentTimeMillis();
    private long timeoutMillis;

    private T responseCommand;

    public ResponseFuture(int opaque) {
        this.opaque = opaque;
    }

    public boolean isTimeout() {
        long diff = System.currentTimeMillis() - this.beginTimestamp;
        return diff > this.timeoutMillis;
    }

    public T waitResponse(final long timeoutMillis) throws InterruptedException {
        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
        return this.responseCommand;
    }

    public void putResponse(final T responseCommand) {
        this.responseCommand = responseCommand;
        this.countDownLatch.countDown();
    }
}
